#!/usr/bin/env python
# coding=utf-8

import json
import os
import traceback
from datetime import datetime

from lib.msg_data import MsgData
from lib.user import User

RECORD_TAG = "记录"
SEARCH_TAG = "查找"
DEL_TAG = "删除"

DATA = "data.json"


# {user: [data1, data2...]}
entity = {}

restored = False


def handle_content(msg, user_name):
    restore_in_first_time()

    ret_msg = ""
    if msg.startswith(RECORD_TAG):
        msg = msg.split(RECORD_TAG, 1)[1]
        ret_msg = _record(msg, user_name)
    elif msg.startswith(SEARCH_TAG):
        msg = msg.split(SEARCH_TAG, 1)[1]
        ret_msg = _search(msg, user_name)
    elif msg.startswith(DEL_TAG):
        msg = msg.split(DEL_TAG, 1)[1]
        ret_msg = _delete(msg, user_name)
    else:
        ret_msg = "ah oh，瓶子君没听懂哦~"

    return ret_msg


def restore_in_first_time():
    global entity
    entity = restore()
    restored = True


def _record(msg, user_name):
    u = entity.get(user_name)
    if u is None:
        u = User(user_name)

    data = MsgData(content=msg, date=datetime.now())
    u.append_data(data)
    entity[user_name] = u
    store(entity)
    ret_msg = "收到，瓶子君已牢牢记住咯!"
    return ret_msg


def _search(msg, user_name):
    ret_msg = "ah oh, 找不到相关的备忘录哦~"
    u = entity.get(user_name)
    if u is None:
        return ret_msg

    data_list = u.match_data(msg)
    msg = combine_msg(data_list)
    if len(msg) != 0:
        ret_msg = "找到备忘录：\n" + msg

    return ret_msg


def combine_msg(data_list):
    msg = ""
    for d in data_list:
        date_str = "%d-%d" % (d.date.month, d.date.day)
        msg += "(%s) %s\n" % (date_str, d.content)

    return msg

def _delete(msg, user_name):
    ret_msg = "ah oh, 找不到相关的备忘录哦~"
    u = entity.get(user_name)
    if u is None:
        return ret_msg

    data_list = u.delete_data(msg)
    msg = combine_msg(data_list)
    if len(msg) != 0:
        ret_msg = "已删除备忘录：\n" + msg

    store(entity)
    return ret_msg

def restore():
    entity = {}

    try:
        with open(DATA) as fp:
            json_data = json.load(fp)

        for (user_name, user) in json_data.items():
            u = User(user_name)
            for data in user:
                date = datetime.strptime(data.get("date"), "%Y-%m-%d %H:%M:%S")
                d = MsgData(content=data.get("content"), date=date)
                u.append_data(d)

            entity[user_name] = u
        return entity

    except Exception as e:
        print(traceback.format_exc())
        return entity


def store(entity):
    json_data = {}
    for (user_name, user) in entity.items():
        u = []
        for data in user.get_data_list():
            d = {}
            d["content"] = data.content
            d["date"] = data.date.strftime("%Y-%m-%d %H:%M:%S")
            u.append(d)
        json_data[user_name] = u

    with open(DATA, "w") as fp:
        json.dump(json_data, fp)
